clear all;

ndraws = 10;
alpha = 0.7; % position-to-position decline in CTR
refctr = [1];
for i=1:11
    refctr = [alpha^i; refctr];
end

randn('seed',2); 

synth = readmatrix('synth-core.csv');

synthpre = [synth zeros(size(synth,1),4)];

for kw = 1:size(synth,1)

    nbids = synth(kw,1);
    m = synth(kw,2);
    stdbid = synth(kw,3);
    
    % Generate ndraws samples and compute their statistics
    v = stdbid^2;
    mu = log((m^2)/sqrt(v+m^2));
    sigma = sqrt(log(v/(m^2)+1));
    draws = normrnd(0,1,ndraws,nbids); % generate ndraws random draws
    
    % Generate the profile of random draws
    vals = exp(mu + sigma*sort(draws(:,1:nbids),2));
                
    % Count the number of bidders above the old reserve price for each observation
    bstats = (sum(vals>0.1,2));
                
    % Now iteratively compute equilibrium bids, using the formula from EOS (2007) modified for the case with reserve prices
    vals = max(vals, 0.1);
    bids = alpha*0.10 + (1-alpha)*vals(:,1);
    for i = 2:(nbids-1)
           bids = [bids alpha*bids(:,i-1)+(1-alpha)*vals(:,i)];
    end
                
    % Now compute the summary statistics for these draws, keeping in mind that
    % observed numbers of bidders will be different for different draws
    mstats =[];
    stdstats =[];
    rps = [];
    for i = 1:ndraws
        if bstats(i) > 1
            mstats = [mstats; mean(bids(i,(nbids-bstats(i)+1):nbids-1))];
            stdstats = [stdstats; std(bids(i,(nbids-bstats(i)+1):nbids-1))];
            if bstats(i) < nbids
                rps = [rps; synth(kw,7) * (bids(i,(nbids-bstats(i)):nbids-1) * refctr(13-bstats(i):12))];
            else
                rps = [rps; synth(kw,7) * ([0.1 bids(i,(nbids-bstats(i)+1):nbids-1)] * refctr(13-bstats(i):12))];
            end
        elseif bstats(i) == 1
            rps = [rps; 0.10*synth(kw,7)];
        elseif bstats(i) == 0
            rps = [rps; 0];
        end
    end
    
    synthpre(kw,:) = [synth(kw,:) mean(bstats) mean(mstats) mean(stdstats) mean(rps)];

end

% Save the resulting data, both as a text file and a Matlab file
writematrix(synthpre);
save synthpre.mat synthpre
